import * as crypto from "crypto";
import {Buffer} from "buffer";
import {CallHandler, ExecutionContext, NestInterceptor} from "@nestjs/common";
import {Observable} from "rxjs";

export class JwtConstant implements NestInterceptor{
    /**
     * 密钥
     */
    public static readonly secretKey: string = "conlin";

    public static readonly expiresIn: string = "24h";

    public static USER: any;

    intercept(context: ExecutionContext, next: CallHandler<any>): Observable<any> | Promise<Observable<any>> {
        const req = context.getArgByIndex(1).req;
        console.log(` ==========> \n 拦截身份信息.... \n URL: ${req.path} \n ==========>`)
        JwtConstant.USER = req.user;
        return next.handle();
    }

    public static getCurrentUser() {
        return JwtConstant.USER;
    }

    public static getUserId() {
        return this.getCurrentUser().userId;
    }

    public static getUserRole() {
        return this.getCurrentUser().roles[0];
    }


    /**
     * 密码加密
     * @param password 明文密码
     * @return encodePassword 加密密码
     */
    public static encryptPassword(password: string) : string {
        if (!password) {
            return '';
        }
        let buffer = Buffer.from(this.secretKey, 'base64');
        // 迭代1024次，长度16，sha1算法
        return (crypto.pbkdf2Sync(password, buffer, 1024, 16, 'sha1').toString('base64'));
    }
}
